package com.bit.book.advice;

import com.bit.book.controller.UserController;
import com.bit.book.model.Result;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        //是否要执行下面的方法(beforeBodyWrite)，可以做不同处理
        //比如：
//        if(returnType.getDeclaringClass().equals(UserController.class)){
//            return false;
//        }
        //false：不执行下面的方法
        //true：执行下面的方法
        return true;
    }

    /**
     * 响应正文写入之前 执行该方法，可以在此次做统一处理，统一数据返回格式。
     *  * @param body 目标方法返回值
     * @param returnType 目标方法返回值类型
     * */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if(body instanceof Result<?>){
            return body;
        }
        //返回数据body类型是String需要处理
        if(body instanceof String){
            try {
                return objectMapper.writeValueAsString(Result.success(body));
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        return Result.success(body);
    }
}
